import fetch from 'dva/fetch';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => ({ data }))
    .catch(err => ({ err }));
}

// ************************ 自定义封装 ********************************//

/**
 * 将url与json参数进行拼装
 * @param {*} url : http://www.baidu.com
 * @param {*} params { name :Caroline}
 * @return http://www.baidu.com?name=Caroline
 */
export const appendUrl = function (url = '/', params = {}) {
  if (JSON.stringify(params) !== '{}') {
      url += url.indexOf('?') >= 0 ? '&' : '?';
      for (var param in params) {
          url += url[url.length - 1] === '?' ? '' : '&';
          url += (param + '=' + params[param]);
      }
  }
  return url;
}

/**
 * GET请求封装
 * @param {*} url 
 * @param {*} data 
 */
export function GET(url, data) {
  return new Promise((resolve, reject) => {
    let fullUrl = appendUrl(url,data)
    request(fullUrl, {
      method: 'GET',
      'Content-type': 'application/json; charset=UTF-8',
    }).then(res => {
      if(res.data.status === 0){
        resolve(res.data.data)
      }else{
        reject(res.data.msg)
      }
    }).catch(e => {
      reject(e)
    })

  })
}

/**
 * POST请求封装
 * @param {*} url 
 * @param {*} data 
 */
export function POST(url, data) {
  return new Promise((resolve, reject) => {
    request(url, {
      method: 'POST',
      'Content-type': 'application/json; charset=UTF-8',
    }).then(res => {
      if(res.data.status === 0){
        resolve(res.data.data)
      }else{
        reject(res.data.msg)
      }
    }).catch(e => {
      reject(e)
    })

  })
}